﻿using System.Web.SessionState;
using System.Web.UI;
using TFSBugTracking.Web.Properties;

namespace TFSBugTracking.Web
{
    /// <summary>
    /// Class used to store and retreive the <see cref="ImpersonatingTfsAdapter"/> into and from a <see cref="HttpSessionState"/>
    /// it provides extension methods for <see cref="Page"/> and <see cref="MasterPage"/> (access the methods by using the namespace <see cref="TFSBugTracking.Web"/>
    /// No session use at the moment... serialization issues
    /// </summary>
    public static class HtmlSessionAwareTfsAdapter
    {
        private static readonly object _lock = new object();
        private static ImpersonatingTfsAdapter _c ;

        /// <summary>
        /// extension method used to provide the tfs adapter from a session store retreived from an ASP.NET Page
        /// </summary>
        /// <param name="control">the currint page to get the adapter from</param>
        /// <returns>the tfs adapter</returns>
        public static ImpersonatingTfsAdapter GetSessionCore(this Page control)
        {
            return GetNewCore(control.Session);
        }

        

        /// <summary>
        /// extension method used to provide the tfs adapter from a session store retreived from an ASP.NET Master Page
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public static ImpersonatingTfsAdapter GetSessionCore(this MasterPage control)
        {
            return GetNewCore(control.Session);
        }

        /// <summary>
        /// creates a new tfs adapter instance using the settings fro the web project
        /// </summary>
        /// <param name="state">state to look for instance or to store it to</param>
        /// <returns>adapter instance to talk to</returns>
        private static ImpersonatingTfsAdapter GetNewCore(HttpSessionState state)
        {
            lock (_lock)
            {
                //do not use Session State anymore -> it fails while serializing the adapter
                return  new ImpersonatingTfsAdapter(Settings.Default.TfsUrl, Settings.Default.ProjectMappingsFile, Settings.Default.UserMappingsFile);
            }
        }
    }
}